using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;
using Crusades.Extensions;
using Crusades.MapView;

namespace Crusades.Map{
  public class CountryList : List<Country>{
    public Country Search(Canvas predicate){
      var q =  this.Where(c => c.Name == predicate.Name).FirstOrDefault();
      return q;
    }


    private delegate void lineWeightDelegate(double thickness);
    private event lineWeightDelegate setLineWeight;

    public void SetLineWeight(double thickness){
      setLineWeight(thickness);
    }
    public CountryList hookupCountries(IMap view){
      //Uri maplocation = new Uri("CountryData.xml",UriKind.Absolute);
      XmlXapResolver resolver = new XmlXapResolver();
      //object o = resolver.GetEntity(maplocation, "", typeof(Stream));
      XmlReader reader = XmlReader.Create("CountryData.xml");
      XDocument countryData = XDocument.Load(reader);

      Brush defaultColor = getBrushFromElement(countryData.Root, "defaultColor");
      var countryList = new CountryList();
      foreach (Canvas canvas in view.MapRoot.Children){
         var country = new Country(canvas);

        if (countryData.Root != null){
          XElement countryElement =
            countryData.Root.Elements()
// ReSharper disable PossibleNullReferenceException
              .Where(x => x.Attribute("iso").Value == country.Name)
// ReSharper restore PossibleNullReferenceException
              .FirstOrDefault();
          if(countryElement==null){
            country.SetBackground(defaultColor);
          }
          else{
            Brush brush = getBrushFromElement(countryElement, "color");
            country.SetBackground(brush);
          }
        }

        setLineWeight += country.SetStrokeThickness;
        countryList.Add(country);
      }
      return countryList;
    }

    private Brush getBrushFromElement( XElement element, string name){
      string defaultColorElement = element.Attribute(name).Value;
      return new SolidColorBrush(defaultColorElement.FromHexString());
    }
  }
}